import csv

import init_api_attribute
import pandas as pd
import send_run_result
from api.cases_script.MakeTestCases import test_report


# There must be a method starting with 'test_', otherwise it cannot be executed
# and warning:Process finished with exit code 0

# file = '../api_info.ini'  This is the relative path in the current file directory
# and cannot be written incorrectly


def exe_case():

    params_path = '../params.csv'
    api_cases_path = '../api_cases/cases.csv'
    row_count = -1
    # f = open(csv_file_path, 'r', encoding='utf-8')

    with open(api_cases_path, 'r') as csvfile:
        api_case_reader = csv.DictReader(csvfile)
        cases_list = []
        for case_row in api_case_reader:
            cases_list.append(case_row)

    with open(params_path, 'r', encoding='utf-8') as csvfile:
        reader = csv.DictReader(csvfile)
        for line in reader:
            i = 0
            for column in line:
                if column == 'actual_res':
                    break
                i += 1

            row_count += 1
            # params is a str object,not json object!!
            # method = params.get('method')

            # params = line['apiparams']
            # delete the first and the last chart
            # params = params[1:-1]

            # convert str to dict
            # dict_obj = ast.literal_eval(params)
            # if isinstance(dict_obj, dict):
            #     method = dict_obj['method']
            #     path = dict_obj['path']
            #     parameters = dict_obj['params']

            # 获取测试用例的步骤casestep
            # case_steps = line['casestep']
            # steps = json.dumps(case_steps, ensure_ascii=False)
            #
            # # 遍历case_step测试步骤
            # for step in steps:
            #     # 获取step字典的desc（步骤描述）
            #     params_desc = step.get('desc')
            #     params_desc_dict = ast.literal_eval(params_desc)
            #     if isinstance(params_desc_dict, dict):
            #         method = params_desc_dict['method']
            #         parameters = params_desc_dict['parameters']
            #         path = params_desc_dict['path']

            # 获取keywords
            keywords = line['keywords']

            method = ''
            parameters = ''
            path = ''

            expect = ''
            # 关键字搜寻
            for case in cases_list:
                if case['keywords'] == keywords:
                    method = case['method']
                    parameters = case['case_param']
                    path = case['path']
                    expect = case['expect']

                    # 执行用例（只执行匹配到keywords的用例）
                    # result = api_request_tool.send_api_request(method, parameters, path)
                    result = '123'
                    # result_dict = ast.literal_eval(result)
                    if isinstance(result, dict):
                        code = result['code']
                        message = result['message']
                        success = result['success']
                        date = result['data']

                    # 保存接口返回的结果到csv文件
                    df = pd.read_csv(params_path)
                    # 获取指定的行 会空值异常
                    # data_at_specified_row = df.iloc[row_count]
                    # 获取指定的行 会空置异常
                    # data_at_specified_column = df['columns_name'] == 'response'
                    df.loc[row_count, 'actual_res'] = str(result)
                    df.loc[row_count, 'expect'] = expect

                    if expect in result:
                        df.loc[row_count, 'is_pass'] = 'success'
                    else:
                        df.loc[row_count, 'is_pass'] = 'fail'
                    df.to_csv(params_path, index=False)

        # 测试报告
        test_report()

        # 执行完用例后，将执行结果发送到测试平台

        task_id = init_api_attribute.get_test_taskid()
        send_run_result.send_result(int(task_id))


def test_exe():
    exe_case()
    print('sss')
